<?php
/**
 * Application level Controller
 *
 * This file is application-wide controller file. You can put all
 * application-wide controller-related methods here.
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Controller
 * @since         CakePHP(tm) v 0.2.9
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */

App::uses('Controller', 'Controller');

/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @package       app.Controller
 * @link http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
 */
class AppController extends Controller {
	
	public  $uses=array('Error','Config','Group','ResourcePage','Resource','FriendlyUrl');
	public  $components = array('Acl','Auth','Common','Session');
	public  $helpers=array('Seo','Html','Form','Session','Js','Common');
	public  $layout=null;
	public  $isAdmin=false;
	public  $isSa=false;
	public $webConfig=array();
	public $webResource=array();
	public function beforeRender(){
		$this->set('uses',$this->uses);
	}
	public function beforeFilter() {
		//parent::beforeFilter();
		//t($this->params,0);
		//t($this->Session->read($this->uses[0].'2'),0);
		
		
		$this->initAuth();
		if(Configure::read('Permission.isCheck'))$this->checkAcl();
		//lay tat ca config tu trong db va set cho view de tien dung trong code.
		$config=$this->Config->find('all');
		
		if(count($config)>0){
			foreach($config as $k=>$v){				
				$this->webConfig[$v['Config']['key']]=$v['Config']['value'];
			}
		}
		$this->set('webConfig',$this->webConfig);
		Configure::write('Config.webConfig',$this->webConfig);
		//===========================================================
		
		
		
		//set default locale if no locale found in session:		
		if(!$this->Session->check('siteLang')){
			$this->Session->write('siteLang',$this->webConfig['siteLang']);
		}
		if(!$this->Session->check('adminLang')){
			$this->Session->write('adminLang',$this->webConfig['adminLang']);
		}
		//custome locale for query string:
		//get all lang
		$alllang=explode(',', $this->webConfig['langs']);
		//check if last param is locale		
		if(count($this->params['pass'])>0 && in_array($this->params['pass'][count($this->params['pass'])-1], $alllang))
			Configure::write('Config.language',$this->params['pass'][count($this->params['pass'])-1]);
		else 
			if(isset($this->params['admin'])){
				Configure::write('Config.language',$this->Session->read('adminLang'));
				//$l10n->__setLanguage($this->Session->read('adminLang'));	
			}		
			else{
				Configure::write('Config.language',$this->Session->read('siteLang'));
				$this->set('locale',Configure::read('Config.language'));
				//$l10n->__setLanguage($this->Session->read('siteLang'));						
			}
		
		//===========================================================
		
		
		
		//get resource		
		$this->ResourcePage->recursive=-1;
		//common
		$pid=2;
		if(isset($this->params['admin']))$pid=1;
		$resourcepage=$this->ResourcePage->find('first',array('conditions'=>array('ResourcePage.name'=>'common','ResourcePage.resource_category_id'=>$pid)));
		//t($resourcepage,0);
		$id=intval($resourcepage['ResourcePage']['id']);
		if($id){
		//get data from resource table
			$options['joins'] = array(
			    array('table' => 'resource_details',
			        'alias' => 'ResourceDetail',
			        'type' => 'left',
			        'conditions' => array(
			            'Resource.id = ResourceDetail.resource_id',
			            'ResourceDetail.locale'=>Configure::read('Config.language')
			        )
			    )
			);
			$options['conditions']=array(
				'Resource.'.$this->Resource->belongsTo['ResourcePage']['foreignKey']=>$id
			);	
			$options['fields']=array('
			`ResourceDetail`.`message`,
			`Resource`.`name`
			
			');		
			$options['order']=array('`Resource`.`id` asc');
			$resource=$this->Resource->find('all',$options);
					
			if(count($resource)>0){
				foreach($resource as $k=>$v){
					$this->webResource[$v['Resource']['name']]=$v['ResourceDetail']['message'];
				}
				Configure::write('Config.webResource',$this->webResource);
			}
		}
		
		//page
		$action=$this->params['action']; 		
 		$controller=$this->name;
		$resourcepage=$this->ResourcePage->find('first',array('conditions'=>array('ResourcePage.name'=>$controller.'/'.$action)));
		
		$id=intval($resourcepage['ResourcePage']['id']);
		if($id){
		//get data from resource table
			$options['joins'] = array(
			    array('table' => 'resource_details',
			        'alias' => 'ResourceDetail',
			        'type' => 'left',
			        'conditions' => array(
			            'Resource.id = ResourceDetail.resource_id',
			            'ResourceDetail.locale'=>Configure::read('Config.language')
			        )
			    )
			);
			$options['conditions']=array(
				'Resource.'.$this->Resource->belongsTo['ResourcePage']['foreignKey']=>$id
			);	
			$options['fields']=array('
			`ResourceDetail`.`message`,
			`ResourceDetail`.`id`,
			`Resource`.`name`,
			`Resource`.`id`
			');		
			$options['order']=array('`Resource`.`id` asc');
			$resource=$this->Resource->find('all',$options);
			if(count($resource)>0){
				foreach($resource as $k=>$v){
					$this->webResource[$v['Resource']['name']]=$v['ResourceDetail']['message'];
				}
				Configure::write('Config.webResource',$this->webResource);
			}
		}
		//===========================================================
		
		
		
	}

	public function initAuth(){
		
 		//$this->Session->write('User',$user);
 		//t($this->Auth->password('admin'));
 		
 		$this->Auth->ajaxLogin='redirectLogin';
 		//t($this->params['admin']);t($this->Session->check('loginRedirect') );
 		if($this->Session->check('loginRedirect') && isset($this->params['admin'])){	  
 			$this->Auth->authenticate =array(
 				AuthComponent::ALL => array(
 					'userModel' => 'User',
 					'fields'=>array('username'=>'username','password'=>'password'),
 					'scope'=>array('User.published' => 1,'Group.published'=>1),
 					'loginAction'=>array('admin' => true,'controller'=>'users','action' => 'login'),
 					
 				),
 				'Form'
 			); 			
 			if($this->Session->read('loginRedirect')=="#users-logout")$this->Session->write('loginRedirect','/');
 			$this->Auth->loginRedirect = SITE_URL.'/'.Configure::read('FakeAdmin').$this->Session->read('loginRedirect');
 		}
	  	else{	  		
	  		$this->Auth->allow('*');	
	  		//visited counter
	  		//$data=$this->Config->findByKey('visited');
	  		//$this->Config->updateAll(array('value'=>($data['Config']['value']+1)),array('key'=>'visited'));
	  	}
	  	$this->user=$this->Auth->user();
	//fix lost session admint($this->params);
		if(isset($this->params['admin']) && $this->params['admin'] && empty($this->user['id']) && ($this->params['controller']!="users" || $this->params['action']!="admin_login")) {
			//check if request is type url.			
			if($this->params['controller']=="homes" && $this->params['action']=="admin_index" && isset($_COOKIE['loginRedirect'])){
				$this->Session->write('loginRedirect',$_COOKIE['loginRedirect']);
				//remove cookie
				setcookie('loginRedirect','',1);				
				$this->redirectTo(SITE_URL.'/'.Configure::read('FakeAdmin').'/users/login');	
			}
			//or request is ajax
			else if($this->params['controller']!="homes" || $this->params['action']!="admin_index"){
				$loginRedirect='#'.$this->params['controller'].'-'.str_replace($this->params['prefix'].'_','',$this->params['action']);
				if(count($this->params['pass'])>0)
					foreach($this->params['pass'] as $k=>$v)$loginRedirect.='-'.$v;
				$this->Session->write('loginRedirect',$loginRedirect);
				$this->redirectTo(SITE_URL.'/'.Configure::read('FakeAdmin').'/users/login');
			}	
			
		}
	  	if($this->user['group_id']==1)Configure::write('Session.isSa',true);
 		else if($this->user['group_id']==4){Configure::write('Session.isAdmin',true);}
	  			
 	}
 	
 	public function checkAcl(){ 		
 		
 		$user=$this->Auth->user();
 		if(!$user['group_id'])$user['group_id']=2;//Anonymous 		 
 		$action=$this->params['action']; 		
		$group =$this->Group;
		$group=$group->findById($user['group_id']);		
 		$controller=$this->name;
 		$methodPath=$this->Common->samePermission('controllers/'.$controller.'/'.$action); 	
 		$this->{$this->uses[0]}->query('SET SESSION SQL_BIG_SELECTS=1');
		//t($this->Acl->check($user['username'],$methodPath,'read'));
 			
 		$isAuthorize=false;		
		//if($user && isset($this->params['admin']) && !in_array($action,$this->Common->baseMethod()) && !in_array($controller,$this->Common->baseController()) && !in_array($controller.'/'.$action,$this->Common->baseMethodController())){			
 		if(!Configure::read('Session.isSa') && !in_array($action,$this->Common->baseMethod()) && !in_array($controller,$this->Common->baseController()) && !in_array($controller.'/'.$action,$this->Common->baseMethodController())){
			$aco =& $this->Acl->Aco;
			
			$node=$aco->node($methodPath);
	 		if($node){
	 			
	 			if(isset($this->params['pass'][0])){
		 			//check acl on record:
		 			$aconame=$controller.$action.$this->params['pass'][0];
	 				$nodeAco=$this->Acl->Aco->node($aconame);
		 			$nodeAro=$this->Acl->Aro->node(array('User'=>$user));
		 			
		 			if(!empty($nodeAco)){
			 			//check acl
			 			$acl=$this->Group->query('select * from aros_acos where aro_id='.$nodeAro[0]['Aro']['id'].' and aco_id='.$nodeAco[0]['Aco']['id']);
			 			//t($methodPath.'/'.$this->params['pass'][0]);
			 			//t('select * from aros_acos where aro_id='.$nodeAro[0]['Aro']['id'].' and aco_id='.$nodeAco[0]['Aco']['id']);
			 			//t($acl);
			 			if(!empty($acl))$methodPath=$aconame;
			 			
		 			}
	 			}
	 			//t($methodPath);
				if ($this->Acl->check(array('User'=>$user),$methodPath,'read')){
					$isAuthorize=true;
	 			}
	 			
	 		}	 			
 		
		}		
		else{
			$isAuthorize=true;
		}
		
		if(!$isAuthorize){
			$this->throwErrorMessage('You are not authorized to access that location');
		}
 		
 	}
 	
 	public function throwErrorMessage($message){
 		if(isset($this->params['admin'])){
 			$this->Session->write('error',_resource($message,true));
			echo '<script>ajaxSubmit("mainContent","errors")</script>';
 		}
 		else{
 			echo '<script>alert("'.$message.'")</script>';
 		}
			exit;
 	}
 	
	public function getLangs($id=null,$model){
		if($id){
			$translateTable='i18n';
			if(!empty($this->{$model}->translateTable))$translateTable=$this->{$model}->translateTable;
			$translateModel=Inflector::camelize($translateTable);
			$rs=$this->{$model}->query('select `'.$translateModel.'`.`locale` from '.$this->Config->tablePrefix.$this->{$model}->table.' '.$model.'
			inner join '.$this->Config->tablePrefix.$translateTable.' '.$translateModel.' on '.$translateModel.'.foreign_key='.$model.'.id
			where '.$translateModel.'.field="'.$this->{$model}->actsAs['Translate'][0].'" 
			and '.$translateModel.'.model="'.$model.'" and '.$model.'.id='.$id);
			$tmp=null;
			foreach($rs as $v){
				$tmp[]=$v[$translateModel]['locale'];
			}
			//t($tmp);
			return $tmp;
		}

	}
	
	public function redirectAjaxTo($action="homes",$content="mainContent",$isBack=false){		
		if($isBack) echo '<script>ajaxSubmit("'.$content.'","'.$action.'")</script>';
		else echo '<script>ajax("'.$content.'","'.$action.'")</script>';
		exit;
	}
	public function redirectTo($action=SITE_URL){	
	
		echo '<script>window.location="'.SITE_URL.$action.'";</script>';
		exit;
	}
public function updateSeoLink($realurl,$title,$id){
		//=================seo link update
		$realurl=strtolower($realurl);
		
		$friendlyUrl=$this->FriendlyUrl->findByRealurl($realurl);
		$friendlyUrl['FriendlyUrl']['realurl']=$realurl;
		
		$url='/'.$this->Common->replaceUnicodeChar($title).'.html';
		$data=null;
		//check is add or update
		$conditions['url']=$url;
		if(isset($friendlyUrl['FriendlyUrl']['id']))
			$conditions['realurl <>']=$realurl;			
		else
			$this->FriendlyUrl->create();
		
		//if exist then rename url
		$data=$this->FriendlyUrl->find('all',array('conditions'=>$conditions));
		
		while (!empty($data))
		{
			$url='/'.$this->Common->replaceUnicodeChar($title.'-'.($id++)).'.html';		
			$conditions['url']=$url;	
			$data=$this->FriendlyUrl->find('all',array('conditions'=>$conditions));
		} 
			
		
		$friendlyUrl['FriendlyUrl']['url']=$url;		
		$this->FriendlyUrl->save($friendlyUrl);
		//update cache
		//=======================================
	}
	
	public function appError($error) {
		
		if(Configure::read('debug')>0)t($error->getMessage());
		$data=array(
			'host'=>$this->request->host(),
			'type'=>'exception',
			'code'=>$error->getCode(),
			'message'=>$error->getMessage(),
			'method'=>$_SERVER['REQUEST_METHOD'],
			'referer'=>$this->request->referer(),
			'here'=>$this->request->here(),
			'clientIp'=>$this->request->clientIp(),
			'input'=>$this->request->input(),
			'HTTP_USER_AGENT'=>$_SERVER['HTTP_USER_AGENT'],
			'HTTP_ACCEPT'=>$_SERVER['HTTP_ACCEPT'],
			'HTTP_COOKIE'=>$_SERVER['HTTP_COOKIE'],
			'CONTENT_TYPE'=>isset($_SERVER['CONTENT_TYPE'])?$_SERVER['CONTENT_TYPE']:'',
			'CONTENT_LENGTH'=>isset($_SERVER['CONTENT_LENGTH'])?$_SERVER['CONTENT_LENGTH']:0,
		);
		
		$this->Error->save($data);
    }
	
}
